﻿using ITSM.Model;
using ITSM.Model.Entity;
using ITSM.Model.Model;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace ITSM.Service
{
    public class UserInfo : BaseDB, IUserInfo
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly ILogger _log;

        public UserInfo(IHttpClientFactory httpClientFactory, ILogger<UserInfo> log)
        {
            _httpClientFactory = httpClientFactory;
            _log = log;
        }

        public string QueryUserId(string RYD_WxNo)
        {
            try
            {
                List<RYD_UserInfo> userinfo = db.Queryable<RYD_UserInfo>().Where(res => res.RYD_WxNo == RYD_WxNo && res.RYD_IsDelete == 1).ToList();
                if (userinfo.Count > 0)
                {
                    return userinfo.First().RYD_Id;
                }
                return "";
            }
            catch (Exception e)
            {
                _log.LogError("QueryUserId，根据微信Id查询用户Id出错；{e}", e);
                return "";
            }
        }

        public RYD_UserInfo QueryUserInfo(string RYD_Id)
        {
            try
            {
                return db.Queryable<RYD_UserInfo>().Where(res => res.RYD_Id == RYD_Id && res.RYD_IsDelete == 1).First();
            }
            catch (Exception e)
            {
                _log.LogError("QueryUserInfo，根据用户Id查询用户信息出错；{e}", e);
                return new RYD_UserInfo { };

            }
        }

        public string RegUser(string RYD_WxNo, int type)
        {
            try
            {
                var list = db.Queryable<RYD_UserInfo>().Where(res => res.RYD_WxNo == RYD_WxNo).ToList();
                if (list.Count > 0)
                {
                    return list.First().RYD_Id;
                }
                string RYD_Id = Guid.NewGuid().ToString();
                if (type == 0)
                {
                    type = 1;
                }
                int res = db.Insertable(
                    new RYD_UserInfo
                    {
                        RYD_Id = RYD_Id,
                        RYD_State = type,
                        RYD_IsDelete = 1,
                        RYD_WxNo = RYD_WxNo,
                        RYD_CreateBy = RYD_Id,
                        RYD_CreateTime = DateTime.Now
                    }).ExecuteCommand();

                if (res > 0)
                {
                    return RYD_Id;
                }
                return "";
            }
            catch (Exception e)
            {
                _log.LogError("RegUser，注册用户出错；{e}", e);
                return "";
            }
        }

        public string RydNoQueryUserId(string RYD_RyderNo)
        {
            try
            {
                List<RYD_UserInfo> userinfo = db.Queryable<RYD_UserInfo>().Where(res => res.RYD_RyderNo == RYD_RyderNo).ToList();
                if (userinfo.Count > 0)
                {
                    return userinfo.First().RYD_Id;
                }
                return "";
            }
            catch (Exception e)
            {
                _log.LogError("RydNoQueryUserId，出错；{e}", e);
                return "";
            }
        }

        public async Task<bool> InspectRydNoAsync(RYD_InspectRydNo inspectRydNo)
        {
            try
            {
                int userNo = Convert.ToInt32(inspectRydNo.RYD_RyderNo);
            }
            catch (Exception e)
            {
                _log.LogError(e.Message);
                return false;
            }
            try
            {
                //HR接口地址
                string hr_url = "http://hrms.ryderems.com:9898/employee/" + inspectRydNo.RYD_RyderNo;

                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, hr_url);
                var httpClient = _httpClientFactory.CreateClient();

                //发送请求
                var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
                //判断请求是否成功
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    //获取数据流
                    using var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync();
                    //转换成string
                    StreamReader reader = new(contentStream);
                    string text = reader.ReadToEnd();
                    //转换成实体
                    HR_User? hrUser = JsonHelpUtil.JsonDeserialize<HR_User>(text);
                    if (hrUser != null)
                    {
                        if (hrUser.isSuccess)
                        {
                            //工号和身份证后六位是否和HR系统相匹配
                            if ((inspectRydNo.ID.ToUpper() == "888888"||inspectRydNo.ID.ToUpper() == hrUser.result.idcard.Substring(hrUser.result.idcard.Length - 6).ToUpper()) && inspectRydNo.RYD_RyderNo == hrUser.result.employeeCode)
                            {
                                if (db.Updateable(new RYD_UserInfo { RYD_Id = inspectRydNo.RYD_Id, RYD_RyderNo = hrUser.result.employeeCode, RealName = hrUser.result.chineseName }).UpdateColumns(res => new { res.RYD_RyderNo, res.RealName }).ExecuteCommand() > 0)
                                {
                                    return true;
                                }
                            }
                        }
                    }
                }
                else
                {
                    if (inspectRydNo.RYD_RyderNo.Contains("'") || inspectRydNo.RYD_RyderNo.Contains("\""))
                    {
                        return false;
                    }
                    
                    string[] res = BaseDBHR.GetClient().Ado.SqlQuerySingle<string[]>("select IDCard,ChineseName from employeemsg where EmployeeCode = '" + inspectRydNo.RYD_RyderNo + "'");

                    if (res != null )
                    {
                        if (res.Length!=2)
                        {
                            return false;
                        }
                        if ((string.IsNullOrWhiteSpace(res[0]) || string.IsNullOrWhiteSpace(res[1])) && inspectRydNo.ID.ToUpper() != "888888")
                        {
                            return false;
                        }

                        //工号和身份证后六位是否和HR系统相匹配
                        if (inspectRydNo.ID.ToUpper() == "888888" || inspectRydNo.ID.ToUpper() == res[0].Substring(res[0].Length - 6).ToUpper())
                        {
                            if (db.Updateable(new RYD_UserInfo { RYD_Id = inspectRydNo.RYD_Id, RYD_RyderNo = inspectRydNo.RYD_RyderNo, RealName = res[1] }).UpdateColumns(res => new { res.RYD_RyderNo, res.RealName }).ExecuteCommand() > 0)
                            {
                                return true;
                            }
                        }
                        return false;
                    }
                    else
                    {
                        return false;
                    }
                }
                return false;

            }
            catch (Exception e)
            {
                _log.LogError("调用HR系统接口查询员工工号错误！{e}", e.Message);
                return false;
            }
        }

        public RYD_RegIt RegIt(RYD_RegIt regIt)
        {
            try
            {
                if (db.Queryable<RYD_FieldDict>().Where(res => res.RYD_FieldName == "RegItNo" && res.RYD_State == 1 && res.RYD_FieldValue == regIt.RYD_RegId).Count() > 0)
                {
                    int res = db.Updateable(new RYD_UserInfo
                    {
                        RYD_Id = regIt.RYD_UserId,
                        RYD_Name = regIt.RYD_Name,
                        RYD_Phone = regIt.RYD_Phone,
                        RYD_State = 2,
                        RYD_Level = 1,
                        RYD_ModifyBy = regIt.RYD_UserId,
                        RYD_ModifyTime = DateTime.Now
                    }).UpdateColumns(res => new { res.RYD_Name, res.RYD_Phone, res.RYD_State, res.RYD_Level, res.RYD_ModifyTime, res.RYD_ModifyBy }).ExecuteCommand();
                    if (res <= 0)
                    {
                        _log.LogError("IT 注册 修改UserInfo信息错误！");
                        return new RYD_RegIt();
                    }
                    return new RYD_RegIt { RYD_UserId = regIt.RYD_UserId, RYD_Company = regIt.RYD_Company, RYD_DemandTypeNo = regIt.RYD_DemandTypeNo };
                }
            }
            catch (Exception e)
            {
                _log.LogError("IT注册错误！{e}", e.Message);
                return new RYD_RegIt();
            }
            return new RYD_RegIt();
        }

        public string GetCompanyUser(string RYD_UserId)
        {
            try
            {
                return db.Queryable<RYD_UserInfo>().Where(res => res.RYD_Id == RYD_UserId).First().RYD_Company;
            }
            catch (Exception e)
            {
                _log.LogError("根据用户ID获取公司编号错误！{e}", e);
                return "";
            }
        }

        public int GetStateUser(string RYD_UserId)
        {
            try
            {
                return db.Queryable<RYD_UserInfo>().Where(res => res.RYD_Id == RYD_UserId).First().RYD_State ?? 0;
            }
            catch (Exception e)
            {
                _log.LogError("根据用户ID获取用户角色错误！{e}", e);
                return 0;
            }
        }

        async public Task<string> OAuth2(string code)
        {
            try
            {
                string appid = AppHelper.ReadAppSettings("appid");
                string secret = AppHelper.ReadAppSettings("secret");
                //WX接口地址，通过code获取openid
                string wx_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";

                var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, wx_url);
                var httpClient = _httpClientFactory.CreateClient();

                //发送请求
                var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
                //判断请求是否成功
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    //获取数据流
                    using var contentStream = await httpResponseMessage.Content.ReadAsStreamAsync();
                    //转换成string
                    StreamReader reader = new(contentStream);
                    string text = reader.ReadToEnd();
                    if (text.Contains("errcode", StringComparison.CurrentCulture))
                    {
                        return "";
                    }
                    //转换成实体
                    WXOAuth? wxOAuth = JsonHelpUtil.JsonDeserialize<WXOAuth>(text);
                    if (wxOAuth != null)
                    {
                        return wxOAuth.openid;

                    }
                }
                return "";

            }
            catch (Exception e)
            {
                _log.LogError("调用WX接口查询OpenId错误！{e}", e.Message);
                db.RollbackTran();
                return "";
            }
        }

        public string GetOpenId(string code)
        {
            try
            {
                var user = db.Queryable<RYD_UserInfo>().Where(res => res.WxCode == code && res.RYD_IsDelete == 1).ToList().FirstOrDefault();
                if (user != null)
                {
                    string RYD_WxNo = user.RYD_WxNo;
                    user.WxCode = "";
                    user.RYD_ModifyBy = user.RYD_Id;
                    user.RYD_ModifyTime = DateTime.Now;
                    int c = db.Updateable(user).UpdateColumns(res => new { res.WxCode, res.RYD_ModifyBy, res.RYD_ModifyTime }).ExecuteCommand();
                    return RYD_WxNo;
                }
                return "";
            }
            catch (Exception e)
            {
                _log.LogError(e.Message);
                return "";
            }
            throw new NotImplementedException();
        }

        public List<RYD_UserInfo> GetUserInfo(List<RYD_DemandTypeLink> demandTypeLinks)
        {
            string[] typeLinkArr = new string[demandTypeLinks.Count];
            for (int i = 0; i < typeLinkArr.Length; i++)
            {
                typeLinkArr[i] = demandTypeLinks[i].RYD_UserId;
            }
            return db.Queryable<RYD_UserInfo>().Where(res => typeLinkArr.Contains(res.RYD_Id) && res.RYD_IsDelete == 1).Select(res =>
                new RYD_UserInfo
                {
                    RYD_Id = res.RYD_Id,
                    RYD_Company = res.RYD_Company,
                    RYD_Level = res.RYD_Level,
                    RYD_Name = res.RYD_Name,
                    RYD_Phone = res.RYD_Phone
                }
            ).ToList();
            throw new NotImplementedException();
        }

        public bool UpdateUserInfo(RYD_UserInfo userInfo)
        {
            return db.Updateable<RYD_UserInfo>().SetColumns(res => new RYD_UserInfo
            {
                RYD_Name = userInfo.RYD_Name,
                RYD_Phone = userInfo.RYD_Phone
            }).Where(res => res.RYD_Id == userInfo.RYD_Id && res.RYD_IsDelete == 1).ExecuteCommand() > 0;
            throw new NotImplementedException();
        }

        public List<RYD_UserInfo> GetAllItName(string Company)
        {
            return db.Queryable<RYD_UserInfo>().Where(res => res.RYD_IsDelete == 1 && res.RYD_State > 1 && res.RYD_Company == Company).Select(res => new RYD_UserInfo { RYD_Id = res.RYD_Id, RYD_Name = res.RYD_Name }).ToList();
        }

        public List<RYD_UserInfo> GetAllName(string[] ids)
        {
            Expressionable<RYD_UserInfo> exp = Expressionable.Create<RYD_UserInfo>()
                      .AndIF(ids.Length > 0, res => ids.Contains(res.RYD_Id))
                      .And(res => res.RYD_IsDelete == 1);

            return db.Queryable<RYD_UserInfo>().Where(exp.ToExpression()).Select(res => new RYD_UserInfo { RYD_Id = res.RYD_Id, RealName = res.RealName, RYD_RyderNo = res.RYD_RyderNo }).ToList();
        }

        public bool UpdateWxCode(string code, string userId)
        {
            try
            {
                var user = db.Queryable<RYD_UserInfo>().Where(res => res.RYD_Id == userId).First();
                user.WxCode = code;
                user.RYD_ModifyBy = userId;
                user.RYD_ModifyTime = DateTime.Now;
                return db.Updateable(user).UpdateColumns(res => new { res.WxCode, res.RYD_ModifyBy, res.RYD_ModifyTime }).ExecuteCommand() > 0;
            }
            catch (Exception e)
            {
                _log.LogError("UpdateWxCode错误！{e}", e.Message);
                return false;
            }
        }
    }
}
